package by.bucha.testproject.service.handlers.impl;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.ResultReceiver;
import by.bucha.testproject.content.ApplicationProvider;
import by.bucha.testproject.service.ApplicationService;
import by.bucha.testproject.service.handlers.BaseHandler;

public class DbUpdateHandler extends BaseHandler {

	@Override
	public void doExecute(final Intent intent, final Context context,
			final ResultReceiver callback) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String uri = intent
						.getStringExtra(ApplicationService.EXTRA_URI);
				String selection = intent
						.getStringExtra(ApplicationService.EXTRA_SELECTION);
				String[] selectionArgs = intent
						.getStringArrayExtra(ApplicationService.EXTRA_SELECTION_ARGS);

				ContentValues values = new ContentValues();

				String modelType = intent
						.getStringExtra(ApplicationService.EXTRA_MODEL_TYPE);

				values.put(ApplicationProvider.EXTRA_MODEL_TYPE, modelType);

				String modelToUpdate = intent
						.getStringExtra(ApplicationService.EXTRA_SERIALIZED_MODEL);

				values.put(ApplicationProvider.EXTRA_DATA, modelToUpdate);

				int number = -1;

				number = context.getContentResolver().update(Uri.parse(uri),
						values, selection, selectionArgs);

				Bundle bundle = new Bundle();
				bundle.putInt(ApplicationService.EXTRA_NUMBER_ROWS_UPDATED,
						number);

				callback.send(SUCCESS_RESPONSE, bundle);
			}
		}).start();
	}
}
